package com.example.mobilesafe.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.mobilesafe.R;
import com.example.mobilesafe.dao.AppInfoDao;
import com.example.mobilesafe.dao.AppLockDao;
import com.example.mobilesafe.domain.AppInfo;

import java.util.ArrayList;
import java.util.List;

public class AppLockActivity extends AppCompatActivity {

    private static final String TAG = "AppLockActivity";

    private Button btn_unlock;

    private Button btn_lock;

    private LinearLayout ll_unlock;

    private LinearLayout ll_lock;

    private TextView tv_unlock;

    private TextView tv_lock;

    private ListView lv_unlock;

    private ListView lv_lock;

    private List<AppInfo> mAppInfoList;

    private List<AppInfo> mLockList;

    private List<AppInfo> mUnLockList;

    private AppLockDao mDao;

    private MyAdapter mLockAdapter;

    private MyAdapter mUnLockAdapter;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            // 6.接收到消息，填充已加锁和未加锁的数据适配器中
            mLockAdapter = new MyAdapter(true);
            lv_lock.setAdapter(mLockAdapter);

            mUnLockAdapter = new MyAdapter(false);
            lv_unlock.setAdapter(mUnLockAdapter);
        }
    };
    private TranslateAnimation mTranslateAnimation;


    class MyAdapter extends BaseAdapter{

        private boolean isLock;

        /**
         * 用于区分已加锁和未加锁应用的标识
         * @param isLock 用于区分已加锁和未加锁应用的标示，true是已加锁，false是未加锁
         */
        public MyAdapter(boolean isLock) {
            this.isLock = isLock;
        }

        @Override
        public int getCount() {
            if (isLock){
                tv_lock.setText("未加锁应用：" + mLockList.size());
                return mLockList.size();
            }else {
                tv_unlock.setText("已加锁应用：" + mUnLockList.size());
                return mUnLockList.size();
            }
        }

        @Override
        public AppInfo getItem(int position) {
            if (isLock){
                return mLockList.get(position);
            }else {
                return mUnLockList.get(position);
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null){
                convertView = View.inflate(getApplicationContext(), R.layout.listview_islock_item, null);
                holder = new ViewHolder();
                holder.iv_icon = convertView.findViewById(R.id.iv_icon);
                holder.tv_name = convertView.findViewById(R.id.tv_name);
                holder.iv_lock = convertView.findViewById(R.id.iv_lock);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
            final AppInfo appInfo = getItem(position);
            final View animationView = convertView; // 执行动画的View
            holder.iv_icon.setBackgroundDrawable(appInfo.getIcon());
            holder.tv_name.setText(appInfo.getName());
            if(isLock){
                holder.iv_lock.setBackgroundResource(R.drawable.lock);
            }else {
                holder.iv_lock.setBackgroundResource(R.drawable.unlock);
            }
            holder.iv_lock.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 0.添加加锁/解锁的动画效果（有bug，动画效果比数据操作慢）
                    // animationView.startAnimation(mTranslateAnimation);
                    // 0.对动画的执行过程做事件监听，监听到动画执行完成后，再去移除集合中的数据，再刷新界面（改进）
                    animationView.startAnimation(mTranslateAnimation);
                    mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            // 0.动画执行结束后调用的方法
                            if (isLock){
                                // 已加锁切换成未加锁
                                // 1.已加锁集合减少一个，未加锁集合添加一个，对象就是getItem方法获取的对象
                                mLockList.remove(appInfo);
                                mUnLockList.add(appInfo);
                                // 2.从已加锁的数据库中删除一条数据
                                mDao.delete(appInfo.getPackagename());
                                // 3.刷新数据适配器
                                mLockAdapter.notifyDataSetChanged();
                                mUnLockAdapter.notifyDataSetChanged();
                            }else {
                                // 未加锁切换成已加锁
                                // 1.已加锁集合增加一个，未加锁集合减少一个，对象就是getItem方法获取的对象
                                mLockList.add(appInfo);
                                mUnLockList.remove(appInfo);
                                // 2.从已加锁的数据库中删除一条数据
                                mDao.insert(appInfo.getPackagename());
                                // 3.刷新数据适配器
                                mLockAdapter.notifyDataSetChanged();
                                mUnLockAdapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });

                }
            });
            return convertView;
        }
    }

    static class ViewHolder{
        ImageView iv_icon;
        TextView tv_name;
        ImageView iv_lock;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_lock);

        // 初始化UI
        initUI();

        // 初始化数据
        initData();

        // 初始化动画事件监听
        initAnimation();
    }

    /**
     * 初始化UI
     */
    private void initUI() {
        btn_unlock = findViewById(R.id.btn_unlock);
        btn_lock = findViewById(R.id.btn_lock);

        ll_unlock = findViewById(R.id.ll_unlock);
        ll_lock = findViewById(R.id.ll_lock);

        tv_unlock = findViewById(R.id.tv_unlock);
        tv_lock = findViewById(R.id.tv_lock);

        lv_unlock = findViewById(R.id.lv_unlock);
        lv_lock = findViewById(R.id.lv_lock);

        btn_unlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.已加锁列表隐藏，未加锁列表显示
                ll_lock.setVisibility(View.GONE);
                ll_unlock.setVisibility(View.VISIBLE);
                // 2.未加锁变成浅色图片，已加锁变成深色图片
                btn_unlock.setBackgroundResource(R.drawable.tab_left_pressed);
                btn_lock.setBackgroundResource(R.drawable.tab_right_default);
            }
        });

        btn_lock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.已加锁列表显示，未加锁列表隐藏
                ll_lock.setVisibility(View.VISIBLE);
                ll_unlock.setVisibility(View.GONE);
                // 2.未加锁变成浅色图片，已加锁变成深色图片
                btn_unlock.setBackgroundResource(R.drawable.tab_left_default);
                btn_lock.setBackgroundResource(R.drawable.tab_right_pressed);
            }
        });
    }

    /**
     * 初始化数据，区分已加锁和未加锁应用的集合
     */
    private void initData() {
        new Thread(){
            @Override
            public void run() {
                // 1.获取所有手机中的应用
                mAppInfoList = AppInfoDao.getAppInfoList(getApplicationContext());
                // 2.区分已加锁应用和未加锁应用
                mLockList = new ArrayList<>();
                mUnLockList = new ArrayList<>();
                // 3.获取数据库中已加锁应用包名的集合
                mDao = AppLockDao.getInstance(getApplicationContext());
                List<String> lockPackageList = mDao.queryAll();
                for (AppInfo appInfo : mAppInfoList) {
                    // 4.如果循环到的应用包名在数据库中，则说明是已加锁应用
                    if (lockPackageList.contains(appInfo.getPackagename())){
                        mLockList.add(appInfo);
                    }else {
                        mUnLockList.add(appInfo);
                    }
                }
                // 5.告知主线程，可以使用维护的数据
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    /**
     * 初始化动画事件监听（平移自身的一个宽度大小）
     */
    private void initAnimation() {
        mTranslateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,1,
                Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0);
        mTranslateAnimation.setDuration(500);
    }
}
